package uit.uthuoc.fragment;

import java.text.Normalizer;
import java.util.ArrayList;

import uit.uthuoc.dal.DrugDAO;
import uit.uthuoc.dal.DrugDTO;
import uit.uthuoc.dal.MIMSClassDTO;
import uit.uthuoc.utils.Config;
import android.annotation.SuppressLint;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.widget.SearchView.OnQueryTextListener;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.uit.uthuoc.R;


public class DrugSearchFragment extends BaseSearchableFragment {
	
	private static final String LOG_ID = "uit.uthuoc.fragment.DrugSearchFragment";
	public static final String ARG_EXTRA = "uit.uthuoc.fragment.DrugSearchFragment.ARG_EXTRA";
	
	private DrugSearchAdapter adapter;
	private ArrayList<DrugDTO> mDrugList;
	private OnQueryTextListener queryListener = new OnQueryTextListener() {
	
		@Override
		public boolean onQueryTextChange(String arg0) {
			if (arg0.length() >= Config.MIN_LENGHT_TO_SEARCH) {
				onSearchButtonClicked(arg0);
			} else {
				adapter.clear();
			}
			return true;
		}

		@Override
		public boolean onQueryTextSubmit(String arg0) {
//			onSearchButtonClicked(arg0);
			mSearchView.clearFocus();
			return false;
		}
	};
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		MIMSClassDTO mims = null;
		if (getArguments() != null) {
			mims = (MIMSClassDTO) getArguments().getSerializable(ARG_EXTRA);
			Log.d(LOG_ID, "Mims is ..." + mims);
		}
		
		if (mims != null) {
			mDrugList = DrugDAO.getDAO().searchDrugByMIMSClass(Integer.toString(mims.getID()));
			Log.d(LOG_ID, "Mims not null. Successfully get all drug name by MIMS class. Total: " + mDrugList.size());
		}
		
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void setQueryListener() {
		mSearchView.setOnQueryTextListener(queryListener);

	}

	@Override
	protected void iniListAdapter() {
		adapter = new DrugSearchAdapter();
		adapter.clear();
		
		if (mDrugList != null) {
			ArrayAdapter<DrugDTO> tempAdapter = new ArrayAdapter<DrugDTO>(getActivity(), android.R.layout.simple_list_item_1, mDrugList);
			setListAdapter(tempAdapter);
		} else {
			setListAdapter(adapter);
		}
	}
	
	private void onSearchButtonClicked(String searchText) {
		
		adapter.clear();
		adapter.setSearchText(searchText);
		
		mDrugList = DrugDAO.getDAO().searchDrugByDrugName(searchText);
				
		for (DrugDTO drugDTO : mDrugList) {
			adapter.add(drugDTO);
		}			
		setListAdapter(adapter);
		
	}
	
	public static DrugSearchFragment newInstance(MIMSClassDTO mims) {
		Bundle args = new Bundle();
		args.putSerializable(ARG_EXTRA, mims);
		
		DrugSearchFragment fragment = new DrugSearchFragment();
		fragment.setArguments(args);
		
		return fragment;
	}
	
	private class DrugSearchAdapter extends ArrayAdapter<DrugDTO> {
		
		private String searchText = "";
		
		public DrugSearchAdapter() {
			super(getActivity(), 0);
		}
		
		public void setSearchText (String text) {
			searchText = text;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			
			DrugDTO item = getItem(position);
			
			if (convertView == null) {
				convertView = getActivity().getLayoutInflater().inflate(R.layout.search_result_layout, null);
			}
			
			TextView tvDrugName = (TextView) convertView.findViewById(R.id.search_result_tvDrugName);
			TextView tvMIMSCLass = (TextView) convertView.findViewById(R.id.search_result_tvMIMSClass);
			
			//String highlightedStr = item.getDrugName().replaceAll(mSearchString, "<font color=\'blue\'>" + mSearchString + "</font>");
			tvDrugName.setText(highlight(searchText, item.getDrugName()));
			tvMIMSCLass.setText(item.getMIMSClass().getMIMSClassName());
			
			
			
			return convertView;
		}
		
		@SuppressLint("NewApi") 
		public CharSequence highlight(String search, String originalText) {
		    // ignore case and accents
		    // the same thing should have been done for the search text
		    String normalizedText = Normalizer.normalize(originalText, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", "").toLowerCase();

		    int start = normalizedText.indexOf(search);
		    if (start < 0) {
		        // not found, nothing to to
		        return originalText;
		    } else {
		        // highlight each appearance in the original text
		        // while searching in normalized text
		        Spannable highlighted = new SpannableString(originalText);
		        while (start >= 0) {
		            int spanStart = Math.min(start, originalText.length());
		            int spanEnd = Math.min(start + search.length(), originalText.length());

		            highlighted.setSpan(new StyleSpan(Typeface.BOLD), spanStart, spanEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

		            start = normalizedText.indexOf(search, spanEnd);
		        }

		        return highlighted;
		    }
		}
		
		
	}
}